"""
This module takes a bunch of Python objects and compiles them into Javascript.

Since this is the "default" module, we don't know much about the object we're
compiling. We will only grab "properties" and ignore everything else.
"""

from pythontojavascript import methodbuilder
from pythontojavascript import ObjectSerializer

def compile(obj):
  js = []

  parseObject(obj)    
  makeObjPublishable(obj)
    
  js.append(buildObject(obj))
  js.append(buildInstanceMethods(obj))
  js.append(buildClassMethods(obj))
  return "\n".join(js)

def template():
  # The default compiler doesn't need any template
  return ""
  
def parseObject(obj):
  for d in dir(obj):
    attr = getattr(obj,d)
    if type(attr) == property:
      ObjectSerializer.addProperty(obj,d)
  
def makeObjPublishable(obj):
  """
  Tells this object what we've used for compiling the Javascript. Later, when
  we try to "publish" or "serialize" this object, we use this list.
  """
  obj._PTJS_serialize = ObjectSerializer.getProperties(obj)
  
def buildObject(obj,specialClassMethods="",
                addToCache="null"):
  variables = []
  obj_name = obj.__name__
  properties = ObjectSerializer.getProperties(obj)
  for p in properties:
    variables.append(p + ":" +  methodbuilder.FUNC_internal % {"name":p})
  return methodbuilder.JS_OBJECT % {"ObjectName":obj_name,
                               "variables":",\n".join(variables),
                               "classmethods":specialClassMethods,
                               "addToCache":addToCache,
                               }
def buildInstanceMethods(obj):
  methods = ObjectSerializer.getInstMethods(obj)
  output = ["// AUTOCOMPILED BY default.py:buildInstanceMethods"]
  for m in methods:
    output.append(m.buildMethod(obj.__name__))
  return "\n".join(output)
  
def buildClassMethods(obj):
  methods = ObjectSerializer.getClassMethods(obj)
  output = ["// AUTOCOMPILED BY default.py:buildClassMethods"]
  for m in methods:
    output.append(m.buildMethod(obj.__name__))
  return "\n".join(output)
    
